<template>
  <div class='boss'>
    <!-- 发布 / 编辑 -->
    <el-form ref="noticeRef" :model="form" :rules="pageType === 'informadd' || pageType === 'informedit' ? rules2 : rules" label-width="80px">
        <el-form-item class="formItem formItem2" label="标题名称" prop="noticeTitle">
          <el-input v-model="form.noticeTitle" placeholder="请输入标题名称" />
        </el-form-item>
        <el-form-item class="formItem formItem2" label="发布范围" prop="releaseScope">
          <!-- 发布范围 -->
          <el-tree-select
              ref="treeRef"
              v-model="form.releaseScope"
              :data="genderOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              check-strictly
              placeholder="请选择发布范围"
              node-key="id"
              multiple
              filterable
          />
        </el-form-item>
<!--      <el-form-item  class="formItem formItem2" v-if="pageType === 'informadd' || pageType === 'informedit'" label="公告类型" prop="type">-->
<!--        <el-select v-model="form.type" placeholder="请选择公告类型">-->
<!--          <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.code"-->
<!--              :label="item.name"-->
<!--              :value="item.code"-->
<!--          />-->

<!--        </el-select>-->
<!--      </el-form-item>-->
        <el-form-item class="formItem formItem3" label="内容">
          <editor v-model="form.noticeContent" :min-height="420" />
        </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button class="createBtn3" @click="cancel">重置</el-button>
      <el-button class="createBtn3" @click="yulan">预览</el-button>
      <el-button class="addBtn2" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick, watch} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {getCurrentInstance} from 'vue';
import {listNotice, getdeptApi, addNotice, delNotice, updateNotice} from '@/api/system/notice.js'
import {useListStore} from '@/store/modules/news.js'
import {ElMessage, ElMessageBox} from 'element-plus'
import {quickCodeChildrenApi} from "@/api/system/dict/type";

const {proxy} = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const newsPut = useListStore()
// pageType :
// policyadd: '发布政策文件',
//     policyedit: '编辑政策文件',
//     newsadd: '发布新闻动态',
//     newsedit: '编辑新闻动态',
//     informadd: '发布通知公告',
//     informedit: '编辑通知公告',
const pageType = route.params.pageType
const type = route.params.type // 动态路由传过来的值用params接收 -1?发布:编辑
console.log(route.params, 'route.params');

// 树形选择器引用
const treeRef = ref(null)
// 表单数据 - 使用 reactive 替代 ref
const form = reactive({
  noticeTitle: '',
  noticeType:'',
  noticeContent: '',
  releaseScope: [],
})

// 新闻/政策
const rules = reactive({
  noticeTitle: [{required: true, message: "标题名称不能为空", trigger: "blur"}],
  releaseScope: [{required: true, message: '请选择发布范围', trigger: 'change',}],
})

// 通知公告
const rules2 = reactive({
  noticeTitle: [{required: true, message: "标题名称不能为空", trigger: "blur"}],
  releaseScope: [{required: true, message: '请选择发布范围', trigger: 'change',}],
  type: [{ required: true, message: '请选择公告类型',trigger: 'change', }],
})
// 获取发布范围下拉信息
const genderOptions = ref([])

const getdeptApiFn = async () => {
  let page = {
    pageNum: 1,
    pageSize: -1,
  }
  let {code, data} = await getdeptApi(page)
  if (code === 200) {
    genderOptions.value = data
  }
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    noticeTitle: undefined,
    noticeContent: undefined,
    releaseScope:undefined,
    noticeType: 2,
  })
  proxy.resetForm('noticeRef')
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['noticeRef'].validate((valid) => {
    if (valid) {
      // 深拷贝表单数据，避免修改原始数据
      const submitData = JSON.parse(JSON.stringify(form))
      submitData.releaseScope = JSON.stringify(submitData.releaseScope)
      submitData.noticeType= pageType === 'informadd' || pageType === 'informedit' ? 1 : pageType === 'newsadd' || pageType === 'newsedit' ? 2 : 3
      if (type === '-1') {

        console.log('执行添加',pageType,submitData)
          addNotice(submitData).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: '添加成功',
                type: 'success',
              })
              router.go(-1)
            }
          })


      } else {

        console.log('执行编辑',pageType)
          submitData.noticeId = type
        submitData.noticeType= pageType === 'informadd' || pageType === 'informedit' ? 1 : pageType === 'newsadd' || pageType === 'newsedit' ? 2 : 3
          updateNotice(submitData).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: '编辑成功',
                type: 'success',
              })
              router.go(-1)
            }
          })

      }
    }
  })
}

const cancel = () => {  //重置
  reset()
}

const yulan = () => {  //预览
  if (form.noticeTitle === '') {
    ElMessage({
      message: '请填写数据后再进行预览',
      type: 'error',
    })
    return false
  }
  newsPut.fetchList(form)
  console.log(form,'打印这个form');
  
  router.push({
    path: `/newsDetailYulan`,
  })
}

// 调试函数：检查树节点是否存在
const checkNodeExists = (id) => {
  let exists = false;

  const traverse = (nodes) => {
    for (const node of nodes) {
      if (node.id === id) {
        exists = true;
        return;
      }
      if (node.children && node.children.length) {
        traverse(node.children);
      }
    }
  };

  traverse(genderOptions.value);
  return exists;
};
let options = ref([])
const quickCodeChildrenApiFn =()=>{  //通过快码获得公告类型
  quickCodeChildrenApi({parentCode:10000}).then(res=>{
    if(res.code===200){
      options.value = res.rows
    }
  })
}
onMounted(async () => {
  quickCodeChildrenApiFn()
  // 1. 先加载部门数据
  await getdeptApiFn()
  if (type === '-1') {
    console.log('执行添加')
    reset()
  } else {
    console.log('执行编辑', newsPut.listData)
    form.noticeTitle = newsPut.listData?.noticeTitle || ''
    form.noticeContent = newsPut.listData?.noticeContent || ''
    form.type = newsPut.listData?.type || ''
    form.releaseScope = JSON.parse(newsPut.listData?.releaseScope) || []
 
    // 2. 处理releaseScope
    // if (newsPut.listData?.releaseScope) {
    //   try {
    //     // 安全解析JSON
    //     const parsed = JSON.parse(newsPut.listData.releaseScope)

    //     // 转换为数字数组
    //     const releaseScopeIds = Array.isArray(parsed)
    //         ? parsed.map(Number)
    //         : Object.values(parsed).map(Number)

    //     console.log("解析后的ID:", releaseScopeIds)

    //     // 检查所有ID是否在树中存在
    //     releaseScopeIds.forEach(id => {
    //       if (!checkNodeExists(id)) {
    //         console.warn(`ID ${id} 在树中不存在`)
    //       }
    //     })

    //     // 设置表单值
    //     form.releaseScope = releaseScopeIds

    //     // 3. 设置选中项 - 使用setTimeout确保DOM更新
    //     setTimeout(() => {
    //       if (treeRef.value) {
    //         console.log("设置选中项:", releaseScopeIds)
    //         treeRef.value.setCheckedKeys(releaseScopeIds)
    //         // ElMessage.success('数据回显成功')
    //       }
    //     }, 300)

    //   } catch (e) {
    //     console.error("解析releaseScope失败:", e)
    //     form.releaseScope = []
    //     ElMessage.error("发布范围数据解析失败")
    //   }
    // }
  }
})

// 4. 添加监听器确保树形数据加载后设置选中项
// watch(genderOptions, (newVal) => {
//   if (newVal.length > 0 && form.releaseScope.length > 0) {
//     setTimeout(() => {
//       if (treeRef.value) {
//         console.log("通过watch设置选中项:", form.releaseScope)
//         treeRef.value.setCheckedKeys(form.releaseScope)
//       }
//     }, 300)
//   }
// }, {deep: true})

// 5. 树形选择器变化时打印调试信息
// watch(() => form.releaseScope, (newVal) => {
//   console.log("树形选择器值变化:", newVal)
// })
</script>

<style lang='scss' scoped>
.boss {
  padding: 20px;
}


  .formItem2 {
    width: 40%;
    .el-select{
      width: 100%
    }
  }


.formItem3 {
    width: 80%;
}
:deep(.editor, .ql-toolbar) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  width: 273px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>